package com.tqjc.system.core.pipeline.thread;

import com.tqjc.system.common.constant.AddTaskConstant;
import com.tqjc.system.common.enums.CarEnum;
import com.tqjc.system.core.pipeline.util.AddTaskUtil;
import com.tqjc.system.core.threadpool.ThreadPoolManager;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @description:  守护线程，随时唤醒因避让而等待的线程
 * @Author: 86195
 * @Date: 2023/12/19 8:56
 **/
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class AddTaskGuardThread extends Thread{

    private CarDoingAddTaskThread thread;

    private CarDoingAddTaskThread otherThread;

    private String workingCarKey;

    private String otherCarKey;

    private CarEnum carEnum;


    @Override
    public void run() {
        while (thread.getState() != State.TERMINATED){
            //自身线程未完成
            try {
                Thread.sleep(1*1000);
                if(thread.getState() == State.WAITING && thread.getLastAct() == AddTaskConstant.ACT_AVOID
                        && otherThread.getLastAct() == AddTaskConstant.ACT_MOVE){
                    //自己线程在等待 && 自己线程是避让  && 对方线程是移动
                    //判断现在是否冲突
                    boolean conflict = AddTaskUtil.isConflict(workingCarKey, otherCarKey, carEnum);
                    if(conflict){
                        //现在不冲突，唤醒线程
                        synchronized (thread){
                            log.info("守护线程key：{}唤醒线程",workingCarKey);
                            thread.notify();
                        }
                    }
                }

            } catch (Exception e){
                log.error("守护线程key：{}运行异常",workingCarKey,e);
            }
        }
        log.info("守护线程key：{}主动守护线程退出",workingCarKey);

        CarProgressLogThread msgThread = CarProgressLogThread.builder().carInfo(workingCarKey)
                .msg("守护线程已完成执行").build();
        ThreadPoolManager.getInstance().execute(msgThread);

    }



}
